package merlin.dao;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;

public class MerlinBlob implements Blob {
    private byte[] blobBytes = new byte[0];

    public MerlinBlob(byte[] bytes) {
        blobBytes = bytes;
    }

    public InputStream getBinaryStream() {
        ByteArrayInputStream in = new ByteArrayInputStream(blobBytes);

        return in;
    }

    public byte[] getBytes(long pos, int length) {
        return getBytes(blobBytes, pos, length);
    }

    public long length() {
        return (long)blobBytes.length;
    }

    public long position(Blob pattern, long start) {
        throw new RuntimeException("MerlinBlob.position: NOT IMPLEMENTED");
    }

    public long position(byte[] pattern, long start) {
        throw new RuntimeException("MerlinBlob.position: NOT IMPLEMENTED");
    }

    public OutputStream setBinaryStream(long pos) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(blobBytes, 0, blobBytes.length);

        return out;
    }

    public int setBytes(long pos, byte[] bytes) {
        pos -= 1;// the first byte is at position 1

        byte[] newBytes = new byte[(int)(pos+bytes.length)];

        for (int i = 0; i < pos; i++) {
            newBytes[i] = blobBytes[i];
        }

        for (int i = 0; i < bytes.length; i++) {
            newBytes[(int)(pos+i)] = bytes[i];
        }

        blobBytes = newBytes;

        return bytes.length;
    }

    public int setBytes(long pos, byte[] bytes, int offset, int len) {
        byte[] newBytes = getBytes(bytes, (long)offset+1, len);

        return setBytes(pos, bytes);
    }

    public void truncate(long len) {
        if ( len < blobBytes.length ) {
            getBytes(blobBytes, (long)1, (int)len);
        }
    }

    public byte[] getBytes(byte[] bytes, long pos, int length) {
        pos -= 1; // the first byte is at position 1

        if ( bytes.length < (pos+length) ) {
            throw new RuntimeException("MerlinBlob.getBytes: Cannot retrive "+length+" bytes from position "+(++pos));
        }

        byte[] out = new byte[length];
        for (int i = 0; i < length; i++) {
            out[i] = bytes[(int)(pos+i)];
        }

        return out;
    }

	public void free() throws SQLException {
		// TODO Auto-generated method stub
		
	}

	public InputStream getBinaryStream(long arg0, long arg1)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}
}